package com.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.entity.Users;
import com.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	UserService us;
	
	@RequestMapping("/login")
	public String login(Users u,HttpSession session){
		Users user = us.getUserByLogin(u);
		if(user != null){
			session.setAttribute("user",user);
			if(user.getStatus()==0){
				return "redirect:/view/main.jsp";
			}else{
				return "redirect:/view/usermain.jsp";
			}
			
		}
		return "/index.html";
	}
	
	@ResponseBody
	@RequestMapping("/list")
	public Map<String, Object> getAll(@RequestParam(defaultValue="1") int page,@RequestParam(defaultValue="5") int rows){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("pageStart", (page-1)*rows);
		params.put("pageSize", rows);
		Map<String, Object> result = us.list(params);
		System.out.println(result);
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value="/curruser")
	public Users curruser(HttpSession session){
		return (Users) session.getAttribute("user");
	}
	
	@ResponseBody
	@RequestMapping(value="/add",produces="text/html;charset=utf-8")
	public String add(Users u){
		if(us.add(u)){
			return "新增成功！";
		}
		return "新增失败！请重试！";
	}
	
	@ResponseBody
	@RequestMapping(value="/delete",produces="text/html;charset=utf-8")
	public String delete(int id){
		if(us.delete(id)){
			return "删除成功！";
		}
		return "删除失败！请重试！";
	}
	
	@ResponseBody
	@RequestMapping(value="/get")
	public Users getById(int id){
		return us.get(id);
	}
	
	@ResponseBody
	@RequestMapping(value="/edit",produces="text/html;charset=utf-8")
	public String edit(Users u){
		if(us.edit(u)){
			return "修改成功！";
		}
		return "修改失败！请重试！";
	}
	
	@ResponseBody
	@RequestMapping(value="/changepwd",produces="text/html;charset=utf-8")
	public String changepwd(Integer userid ,String newpwd,String oldpwd){
		Users user = us.get(userid);
		if(user != null){
			if(user.getPwd().equals(oldpwd)){
				user.setPwd(newpwd);
				if(us.changePwd(user)){
					return "修改成功！";
				}
			}else{
				return "原密码错误，请重新输入！";
			}
		}
		return "修改失败！请重试！";
	}
	
	@ResponseBody
	@RequestMapping(value="/resetpwd",produces="text/html;charset=utf-8")
	public String resetpwd(int id){
		Users user = new Users();
		user.setUserid(id);
		user.setPwd("12345");
		if(us.changePwd(user)){
			return "重置成功！";
		}
		return "重置失败！请重试！";
	}
}
